<?php
function parse_system_config($file) {
	if (file_exists($file)) {
		require_once($file);
		if (isset($C)) {
			$Q = $C;
			if (isset($Q{'icons'})) {
				$label = $Q{'icons'}{'label'};
				$location = $Q{'icons'}{'location'};
				$Q['icons']['map'] = load_icon_map($Q);
			} else {
				echo "Q icons not set.";
			}
			return $Q;
		} else {
			return null;
		}
	} else {
		return null;
	}
}
function parse_auth_providers($file) {
	if (file_exists($file)) {
		require_once($file);
		if (isset($provider)) {
			return $provider;
		} else {
			return null;
		}
	} else {
		return null;
	}
}
function load_icon_map($Q) {
	if (isset($Q{'icons'})) {
		$mapfile = $Q{'absolute_path'}."/".$Q{'icons'}{'location'}."/".$Q{'icons'}{'label'}.".iconmap.php";
		if (file_exists($mapfile)) {
			include($mapfile);
			if (isset($C)) {
				return $C;
			} 
		}
	}
}
function RandomString($len){
    $randstr = '';
    srand((double)microtime()*1000000);
    for($i=0;$i<$len;$i++){
        $n = rand(48,120);
        while (($n >= 58 && $n <= 64) || ($n >= 91 && $n <= 96)){
            $n = rand(48,120);
        }
        $randstr .= chr($n);
    }
    return $randstr;
}
function strip_html_tags( $text )
{
    $text = strip_tags($text);
    $text = preg_replace(
        array(
          // Remove invisible content
            '@<head[^>]*?>.*?</head>@siu',
            '@<style[^>]*?>.*?</style>@siu',
            '@<script[^>]*?.*?</script>@siu',
            '@<object[^>]*?.*?</object>@siu',
            '@<embed[^>]*?.*?</embed>@siu',
            '@<applet[^>]*?.*?</applet>@siu',
            '@<noframes[^>]*?.*?</noframes>@siu',
            '@<noscript[^>]*?.*?</noscript>@siu',
            '@<noembed[^>]*?.*?</noembed>@siu',
          // Add line breaks before and after blocks
            '@</?((address)|(blockquote)|(center)|(del))@iu',
            '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu',
            '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu',
            '@</?((table)|(th)|(td)|(caption))@iu',
            '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu',
            '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu',
            '@</?((frameset)|(frame)|(iframe))@iu',
        ),
        array(
            ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
            "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0",
            "\n\$0", "\n\$0",
        ),
        $text );
    return strip_tags( $text );
}
function GetSafeValue($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = null) 
{
	
  switch ($theType) {
    case "simplehtml":
      $htmltemp = strip_tags($theValue,"<p><a><ul><ol><li>");
      $theValue = $htmltemp;
  	$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  	$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
      $theValue = ($theValue != "") ? $theValue : "";
    break;
    case "specialtext":
	$htmltemp = strip_html_tags($theValue);
	$theValue = $htmltemp;
  	$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  	$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
      $theValue = ($theValue != "") ? $theValue : "";
      break;
     case "simple":
    case "text":
	$htmltemp = strip_html_tags($theValue);
	$htmltemp = htmlentities($theValue,ENT_QUOTES);
	$theValue = $htmltemp;
  	$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  	$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
      $theValue = ($theValue != "") ? $theValue : null;
      break;    
    case "long":
    case "int":
	$htmltemp = strip_html_tags($theValue);
	$htmltemp = htmlentities($theValue,ENT_QUOTES);
	$theValue = $htmltemp;
  	$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  	$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
      $theValue = ($theValue != "") ? intval($theValue) : 0;
      break;
    case "double":
	$htmltemp = strip_html_tags($theValue);
	$htmltemp = htmlentities($theValue,ENT_QUOTES);
	$theValue = $htmltemp;
  	$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  	$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
      $theValue = ($theValue != "") ? doubleval($theValue) : null;
      break;
    case "date":
	$htmltemp = strip_html_tags($theValue);
	$htmltemp = htmlentities($theValue,ENT_QUOTES);
	$theValue = $htmltemp;
  	$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  	$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
      $theValue = str_replace("&#39;","",$theValue);
      $theValue = ($theValue != "") ? $theValue : null;
      break;
    case "defined":
	$htmltemp = strip_html_tags($theValue);
	$htmltemp = htmlentities($theValue,ENT_QUOTES);
	$theValue = $htmltemp;
  	$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  	$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
if (function_exists("filter_input")) { // php 5.2+ function check
	//include php 5.3 filter based code
	function GetParam($label,$type='int',$source='get') {
	$param = null;
		$internal = null;
		$source = strtolower($source);
		$SRC = null;
		$filter = null;
		switch ($source) {
			case "get":
				$SRC = INPUT_GET;
			break;
			case "post":
				$SRC = INPUT_POST;
			break;
			case "server":
				$SRC = INPUT_SERVER;
			break;
			case "session":
				$filter = null;
				switch ($type) {
					case "int":
						$filter = FILTER_SANITIZE_NUMBER_INT;
					break;
					case "text":
						$filter = FILTER_SANITIZE_STRING;
					break;
					//case "date":
						//$internal = filter_input(INPUT_GET,$label,);
					//break;
					case "email":
						$filter = FILTER_SANITIZE_EMAIL;
					break;
					case "url":
						$filter = FILTER_SANITIZE_URL;
					break;
					case "html":
						$filter = array(FILTER_SANITIZE_SPECIAL_CHARS,ENCODE_HIGH);
					break;
					case "simple":
						$filter = FILTER_SANITIZE_STRIPPED;
					break;
					case "raw":
						$filter = FILTER_UNSAFE_RAW;
					break;
				}
				if ($filter) {
					return filter_var($_SESSION[$label],$filter);
				} else {
					return null;
				}
			break;
			case "env":
				$SRC = INPUT_ENV;
			break;
		}
		switch ($type) {
					case "int":
						$internal = filter_input($SRC,$label,FILTER_SANITIZE_NUMBER_INT);
					break;
					case "text":
						$internal = filter_input($SRC,$label,FILTER_SANITIZE_STRING);
					break;
					//case "date":
						//$internal = filter_input(INPUT_GET,$label,);
					//break;
					case "email":
						$internal = filter_input($SRC,$label,FILTER_SANITIZE_EMAIL);
					break;
					case "url":
						$internal = filter_input($SRC,$label,FILTER_SANITIZE_URL);
					break;
					case "simplehtml":
					case "html":
						$internal = filter_input($SRC,$label,FILTER_SANITIZE_SPECIAL_CHARS,ENCODE_HIGH);
					break;	
					case "simple":
						$internal = filter_input($SRC,$label,FILTER_SANITIZE_STRIPPED);
					break;
					case "raw":
						$internal = filter_input($SRC,$label,FILTER_UNSAFE_RAW);
					break;
		}
		$param = $internal;
	return $param;
	}
} else {
	//include php < 5.2 code
	function GetParam ($FIELD="id",$TYPE="int",$METHOD="GET") {
	switch ($TYPE) {
	 case "int": $value = 0; break;
	 case "text": $value = NULL; break;
	 case "date": $value = NULL; break;
	 default: $value = 0; break;
	}
	switch ($METHOD) {
	 case "post":
	 case "POST":
		if (isset($_POST)) {
		 if (isset($_POST{$FIELD})) {
			$value = GetSafeValue($_POST{$FIELD},$TYPE);
		 }
		}
		break;
	 case "server":
	 case "SERVER":
		    if (isset($_SERVER)) {
		 if (isset($_SERVER{$FIELD})) {
			$value = GetSafeValue($_SERVER{$FIELD},$TYPE);
		 }
		}
	 break;
	 case "session":
	 case "SESSION":
		if (isset($_SESSION)) {  
		 if (isset($_SESSION{$FIELD})) {
			$value = GetSafeValue($_SESSION{$FIELD},$TYPE);
		 }
		}
		break;
	 default: //GET
		if (isset($_POST)) {
		 if (isset($_GET{$FIELD})) {
			$value = GetSafeValue($_GET{$FIELD},$TYPE);
		 }
		}
		break;
	}
	return $value;
	}
}
/* User Functions */
function generate_user_UID($dblayer) {
	$UID = null;
	$control = 200;
	$found = false;
	$i = 0;
		do {
			$iUID = strtoupper(RandomString(6))."-".strtoupper(RandomString(6))."-".strtoupper(RandomString(6))."-".strtoupper(RandomString(6));
			$result = $dblayer->query("USER",sprintf("select UID from users where UID = '%s'",$iUID));
			if (!$result->num_rows) {
				$found = true;
			}
		$i++;
		} while ((!$found) and ($i < $control));
		if ($found) {
			$UID = $iUID;
		}
	return $UID;
}
function group_label($dblayer,$gid) {
	$label = null;
	$result = $dblayer->query("USER",sprintf("select label from groups where gid=%d",$gid));
	if ($result) {
		$row = $result->fetch_object();
		$label = $row->label;
	}
	return $label;
}
function ldap_group_mappings_for_user($default,$providers,$username,$source) {
$groups = array();
	$source_config = $providers->provider_config($source);
	if ($source_config) {
		if (isset($source_config{'maps'})) {
			if (isset($source_config{'auth'}{'username_label'})) {
				$filter = $source_config{'auth'}{'username_label'}."=".$username;
				$attr = array("memberof");
				if ( (isset($source_config['server']['host'])) and (isset($source_config['server']['port'])) ) {
					$lconn = ldap_connect($source_config['server']['host'],$source_config['server']['port']);
					if ($lconn) {
						if (isset($source_config['ldap_provider'])) {
							switch ($source_config['ldap_provider']) {
									case "ms-active-directory":
											ldap_set_option($lconn, LDAP_OPT_PROTOCOL_VERSION,3);
											ldap_set_option($lconn, LDAP_OPT_REFERRALS,0);
									break;
							}// switch ldap_provider
							if ( (isset($source_config['admin']['fqdn'])) and (isset($source_config['admin']['dn'])) and (isset($source_config['admin']['user'])) and (isset($source_config['admin']['pass'])) ) {
								$bound = ldap_bind($lconn,$source_config['admin']['user']."@".$source_config['admin']['fqdn'],$source_config['admin']['pass']);// or die("Cannot Bind to Directory server!");
								if ($bound) {
									$sResult = ldap_search($lconn,$source_config['admin']['dn'], $filter, $attr);// or die("Unable to search LDAP server");
									if ($sResult) {
		      					$entries = ldap_get_entries($lconn, $sResult);
		      					ldap_unbind($lconn);
		      					foreach($entries[0]['memberof'] as $member) {
		      						foreach($source_config['maps'] as $map) {
		      							if ( strpos($member, $map['dn']) ) {
		      								if (!in_array($map['group'],$groups)) {
		      									$groups[] = $map['group'];
		      								}
		      							}
		      						}//foreach
		      					}//foreach entries memberof as $member
		      				}// if sResult
        				}//if bound
							}// admin fqdn and admin user and admin pass
						}//if ldap_provider
					}//if lconn
				}// if server host and server port
			}// if auth username_label
		}// if source_config maps
	}// if source_config
return $groups;
}
function synchronise_user($dblayer,$providers,$info,$source) {
	// this will create a user from a specified authentication source.
		//echo "<p>Synchronising ...</p>\n";
	$UID = null;
	/*$dbname = $default->param("USER","dbname");
	$dbconn = $default->param("USER","dbconn");*/
	//if (($dbname) and ($dbconn)) {
		// check that we can insert this user into the local database
		$username = "";
		$realname = "";
		if (isset($info['username'])) {
			$username = $info['username'];
		}
		if (isset($info['realname'])) {
			$realname = $info['realname'];
		}
		$exR = $dblayer->query("USER",sprintf("select * from users where username = '%s'",$username));
		if (!$exR->num_rows) {
			//echo "<p>User not in users</p>\n";
			//check for archived record
			$archR = $dblayer->query("USER",sprintf("select * from archived_users where username = '%s'",$username));
				if (!$archR->num_rows) {
					//echo "<p>User not in archived_users</p>\n";
					//insert synchronised user
					$uid = generate_user_UID($dblayer);
					$password = md5(RandomString("24"));
					if ($uid) {
						//echo "<p>uid is valid : {$uid}</p>\n";
						//$in->setquery($dbname,$dbconn,sprintf("insert into users (username,password,realname,UID,source,enabled) values ('%s','%s','%s','%s','%s',1)",$username,$password,$realname,$uid,$source),1);
						$inR = $dblayer->query("USER",sprintf("insert into users (username,password,realname,UID,source,enabled) values ('%s','%s','%s','%s','%s',1)",$username,$password,$realname,$uid,$source));
						$id = $inR['insert_id'];
							//echo "<p>id:{$id}</p>\n";
						if ($id) {
							//echo "<p>id is valid {$id}</p>\n";
							$UID = $uid;
							//now setup the groups
							$authSource = $providers->provider_config($source);
							$type = $providers->type($source);
							switch ($type) {
							case "mysql":
								//group mappings ?
								$groups = $authSource['groupMap'];
								foreach ($groups as $group) {
									$exgR = $dblayer->query("USER",sprintf("select * from group_members where id = %d and gid = %d",$id,$group));
									if (!$exgR->num_rows) {
										$ingR = $dblayer->query("USER",sprintf("insert into group_members (gid,id) values (%d,%d)",$group,$id));
									}
								}//foreach groups as group
							break;
							case "ldap":
								//lookup ldap group mappings ?
							//break;
							case "ldaps":
								//lookup ldap group mappings ?
								$mapcount = count($authSource{'maps'});
								if ($mapcount) {
									//there are group mappingss to add
									$groups = ldap_group_mappings_for_user($dblayer,$providers,$username,$source);
									if (count($groups)) {
										//add user to group association table
										/** TODO **/
										foreach ($groups as $group) {
											$exgR = $dblayer->query("USER",sprintf("select * from group_members where id = %d and gid = %d",$id,$group));
											if (!$exgR->num_rows) {
												$ingR = $dblayer->query("USER",sprintf("insert into group_members (gid,id) values (%d,%d)",$group,$id));
											}
										}//foreach groups as group
									}//if count groups
								}//if mapcount
							break;
							}//switch type
						}//if id
					}//if uid
				} else {
					//user is currently archived!
				}
		}//if !ex->totalRows
	//}//if dbname and dbconn
	// returns UID field
	return $UID;
}//synchronise_user();
function update_synchronised_user() {
	// this will check that the real_name, email and other details are synchronised with the authentication source.
}
function archive_user($Q,$dblayer,$providers,$params=null) {
$page = "";
	// this will copy a user to a archived table of users
	$current = current_user($dblayer);
	if (isset($params['UID'])) {
		if ($current['UID'] != $params['UID']) {
			//lookup current user by UID
			$info = user_info($dblayer,$params['UID']);
			//create a new record for this user in the archived_users table
			if (isset($info['archived'])) {
				if (!$info['archived']) {
				 //current user, let's archive them
				 $lookup = $dblayer->query("USER",sprintf("select * from archived_users where UID = '%s'",$params['UID']));
				 	if (!$lookup->num_rows) {
				 		//create archived record and delete from database
				 		$ins = $dblayer->query("USER",
				 			sprintf("insert into archived_users (UID,username,password,realname,source,enabled) values ('%s','%s','%s','%s','%s',%d)",
				 				$info['UID'],
				 				$info['username'],
				 				md5(RandomString("24")),
				 				$info['realname'],
				 				$info['source'],
				 				0
				 				));
				 		
				 		$page .= "<p class=\"ok\">User ".$info['realname']." has been archived</p>\n";
				 		$del = $dblayer->query("USER",sprintf("delete from users where UID = '%s'",$params['UID']));
				 		$del = $dblayer->query("USER",sprintf("delete from group_members where id = %d",$info['id']));
				 		$page .= "<p class=\"ok\">User ".$info['realname']." has been removed from the active users table</p>\n";
				 	} else {
				 		//already archived
				 		$page .= "<p class=\"warning\">User ".$info['realname']." has already been archived</p>\n";
				 	}
				} else {
					//this user is already archived!
					$page .= "<p class=\"warning\">User ".$info['realname']." has been archived</p>\n";
				}
			}//if isset archived
		} else {
			$page .= "<p class=\"warning\">You cannot archive the user you are logged in as!</p>\n";
		}
	}//if isset params UID
	return $page;
}//
function delete_user() {
	// this will delete a user and invoke all deletion routines from other modules for this user
}
function create_user() {
	// this will create a local safe-harbour user.
}
/* End: User Functions */
function current_user($dblayer) {
	//returns array containing the current user's info
	$info = array();
	if (isset($_SESSION)) {
		if (isset($_SESSION['SH-UID'])) {
			$UID = GetParam("SH-UID","text","SESSION");
			if ($UID) {
				$u = $dblayer->query("USER",sprintf("select * from users where UID = '%s'",$UID));
					if ($u->num_rows) {
						$row = $u->fetch_object();
						$info['username'] = $row->username;
						$info['realname'] = $row->realname;
						$info['UID'] = $row->UID;
						$info['id'] = $row->id;
						$info['source'] = $row->source;
						$info['enabled'] = $row->enabled;
					}
			}
		}
	}
	return $info;
}
function user_info($dblayer,$UID) {
	//returns array containing the specified user's info
	$info = array();
	if ($UID) {
		//lookup user
		$u = $dblayer->query("USER",sprintf("select * from users where UID = '%s'",$UID));
			if ($u->num_rows) {
				$row = $u->fetch_object();
				$info['username'] = $row->username;
				$info['realname'] = $row->realname;
				$info['UID'] = $row->UID;
				$info['id'] = $row->id;
				$info['source'] = $row->source;
				$info['enabled'] = $row->enabled;
				$info['archived'] = false;
			} else {
				//check for an archived user
				$archive = $dblayer->query("USER",sprintf("select * from archived_users where UID = '%s'",$UID));
					if ($archive->num_rows) {
						$info['username'] = $row->username;
						$info['realname'] = $row->realname;
						$info['UID'] = $row->UID;
						$info['id'] = $row->id;
						$info['source'] = $row->source;
						$info['enabled'] = $row->enabled;
						$info['archived'] = true;
					}
			}
	}
	return $info;
}
function get_user_groups($dblayer,$id,$context=null) {
	$groups = array();
		if ($context) {
			$permitted_module_members = permitted_module_members($dblayer,$context);
			$pmmList = array_to_query_list($permitted_module_members);
			$g = $dblayer->query("USER",sprintf("select gid from group_members where id=%d and gid IN %s",$id,$pmmList));
				if ($g->num_rows) {
					while ($row = $g->fetch_object()) {
						$groups[] = $row->gid;
					}//while
				}
		} else {
			//$g->setquery($usrdb,$usrconn,sprintf("select gid from group_members where id=%d",$id));
			$g = $dblayer->query("USER",sprintf("select gid from group_members where id=%d",$id));
				if ($g->num_rows) {
					while ($row = $g->fetch_object()) {
						$groups[] = $row->gid;
					}//while
				}
		}
	return $groups;
}
/* Theme Loading */
function load_themefile($themefile,$page) {	
	if (file_exists($themefile)) {
			require_once($themefile);
	}
}
function load_theme($Q,$dblayer,$thid,$params=null) {
	if ($thid) {
		$title = "";
		if (isset($params['title'])) {
			$title = $params['title'];
		}
		$body = "";
		if (isset($params['body'])) {
			$body = $params['body'];
		}
		$htmltitle = null;
		if (isset($params['html-title'])) {
			$htmltitle = $params['html-title'];
		}
		$localtasks = null;
		if (isset($params['local-tasks-html'])) {
			$localtasks = $params['local-tasks-html'];
		}
		$theme = $dblayer->query("SYSTEM",sprintf("select * from themes where thid = %d and enabled = 1",$thid));
			if ($theme->num_rows) {
				$row = $theme->fetch_object();
				$themefile = $Q{'absolute_path'}."/".$row->location."/themes/".$row->themeref."/theme.php";
				$themepath = $row->location."/themes/".$row->themeref;
				$baseurl = $Q{'base_url'};
				$page = array();
				$page['sitename'] = system_get_var($dblayer,"system_sitename");
				$page['title'] = $title;
				$page['html-title'] = $htmltitle;
				$page['body'] = $body;
				$page['baseurl'] = $baseurl;
				$page['themepath'] = $themepath;
				$page['head-scripts'] = $Q['head']['scripts'];
				$page['head-css'] = $Q['head']['css'];
				$page['breadcrumb'] = breadcrumb($Q,$dblayer);
				$page['local-tasks-html'] = $localtasks;
				load_themefile($themefile,$page);
			}
	}
}
function default_theme($dblayer) {
	$thid = system_get_var($dblayer,"system_default_theme");
	return $thid;
}
/* Breadcrumb routines */
function breadcrumb($Q,$dblayer) {
$entry = array();
$entries = array();
	//examine the url and it's parameters and decide what the breadcrumb should be.
	if (isset($_GET['module'])) {
		//lookup modref
		$modref = GetParam("module","text","GET");
		if (function_exists("{$modref}_breadcrumb")) {
			//call the local function's breadcrumb routine.
			$params = array();
			$params['modref'] = $modref;
			$crumbEval = "\$entries = {$modref}_breadcrumb(\$Q,\$dblayer,\$params);";
			eval($crumbEval);
		} else {
				$module = $dblayer->query("SYSTEM",sprintf("select title from modules where modref='%s' and enabled = 1",$modref));
					if ($module->num_rows) {
						$row = $module->fetch_object();
						$entry['label'] = "cPanel";
						$entry['link'] = $Q{'base_url'};
						$entries[] = $entry;
				
						$entry['label'] = $row->title;
						$entry['link'] = $Q{'base_url'}."/?module=".$modref;
						$entries[] = $entry;
						if (isset($_GET{'task'})) {
							$entry['label'] = GetParam("task","text","GET");
							$entry['link'] = "#";
							$entries[] = $entry;
						}
			} else {
				$entry['label'] = "cPanel";
				$entry['link'] = null;
				$entries[] = $entry;
			}
		}
	}
	return $entries;
}
/* System Parameters */
function system_get_var($dblayer,$variable) {
$var = null;
	if ($variable) {
		$v = $dblayer->query("SYSTEM",sprintf("select data from variables where label = '%s' order by varid ASC LIMIT 1",$variable));
			if ($v) {
				$row = $v->fetch_object();
				$var = $row->data;
			}
	}
return $var;
}
/* Array <=> DB Functionality */
function array_to_query_list($list) {
$html = "";
	$count = count($list);
	if ($count) {
	$i = 0;
		$html .= "(";
		do {
			if ($i == ($count-1)) {
				$html .= $list[$i];
			} else {
				$html .= $list[$i].",";
			}
		$i++;
		} while ($i < $count);
		$html .= ")";
	} else {
		$html .= "(0)";
	}
return $html;
}
/** TODO: build_query_list is deprecated, use build_query_list in the dblayer class **/
function build_query_list($db_name,$db_conn,$query,$list_field) {
// will be implemented in class::DBLAYER
	$query_list = new mysqldb;
	$query_list->setquery($db_name,$db_conn,$query);
	$build_list = "(";
	if ($query_list->totalRows > 0) {
		$my_i = 1;
		do {
			$build_list .= $query_list->row{$list_field};
			if (($query_list->totalRows - $my_i) > 0) {
				$build_list .= ",";
			}
			$my_i++;
		} while ($query_list->row = mysql_fetch_assoc($query_list->query));
	} else {
		$build_list .= "0";
	}	
	$build_list .= ")";
	$query_list->disposequery();
return $build_list;
}
/* Custom Theming */
function theme($Q,$default,$input,$params) {
$html = "";
	//look for a custom defined theme function or use the default
	$modref = null;
	if (isset($params['modref'])) {
		$modref = $params['modref'];
	}
	$profile = null;
	if (isset($params['profile'])) {
		$profile = $params['profile'];
	}
	if (function_exists("{$modref}_theme_{$profile}")) { // example : cpanel_theme_icon
		$themecode = "\$Thtml = {$modref}_theme_{$profile}(\$Q,\$default,\$input,\$params);";
		eval($themecode);
		if (isset($Thtml)) {
			$html = $Thtml;
		}
	} else {
		//standard themeing
		switch ($profile) {
			case "local-task":
				if ($input['link'] == null) {
					$dividerTitle = "";
					if ($input['label'] != null) {
						$dividerTitle = "<h2>".$input['label']."</h2>\n";
					}
					$html .= "<div class='clearboth'>{$dividerTitle}</div>\n";
				} else {
					$html .= "<div class='local-task-outer'><a href='".$input['link']."'><img src='".$input['icon']."' /></a><br /><a href='".$input['link']."'>".$input['label']."</a></div>\n";
				}
			break;
		}
	}
return $html;
}
/* Result Pagers */
function result_pager($dblayer,$dblabel,$query,$url,$maxRows=10,$maxPageLinks=10,$pageNum=0,$urlSuffix="") {
$html = "";
  $startRow = $pageNum * $maxRows;
  $allReg = $dblayer->query($dblabel,$query);
  $totalRows = $allReg->num_rows;
  if (($totalRows) and ($maxRows)) {
    $totalPages = ceil($totalRows/$maxRows)-1;
  } else {
    $totalPages = 0;
  }
  $linkoffset = 5;
  if ($pageNum > $linkoffset) {
    $i = ($pageNum-$linkoffset);
  } else if ($pageNum) {
    $i = $pageNum;
  }
  
  if ($pageNum <= $linkoffset) {
		$i=0;
	}
	
	if ($totalPages) {
		$html .= "<p>\n";
		$html .= "Go To Page : ";
		if ($pageNum > $linkoffset) {
			$html .= "<a href='{$url}&page=0{$urlSuffix}' class='pager-page-link-first'>First Page</a>";
		}
		
		while (($i <= $totalPages) and ($i <= ($maxPageLinks + $pageNum))) {
		  if ($i <> $pageNum) { 
	      $html .= "<a href='{$url}&page={$i}{$urlSuffix}' class='pager-page-link'>{$i}</a>";
	    } else {
	      $html .= "<span class='pager-page-link-current'>{$i}</span>";
	    }
		$i++;
		}//while
		if (($totalPages > $maxPageLinks) and ($pageNum < $totalPages)) {
			//we are showing the '...', last
	// 		$html .= "...";
			$html .= "<a href='{$url}&page={$totalPages}{$urlSuffix}' class='pager-page-link-last'>Last Page</a>&nbsp;<em>({$totalPages})</em>";
		}
		$html .= "</p>\n";
	}
	
return $html;
}
function setupPagerParams(&$maxRows,&$maxPageLinks,&$pageNum,&$startRow) {
// $maxRows = 10;
//   $maxPageLinks = 10;
//   $pageNum = 0;
  
  if (isset($_POST{'maxRows'})) {
    $maxRows = GetParam("maxRows","int","POST");
  } else if (isset($_GET{'maxRows'})) {
    $maxRows = GetParam("maxRows","int","GET");
  }
  if (isset($_POST{'maxPageLinks'})) {
    $maxPageLinks = GetParam("maxPageLinks","int","POST");
  } else if (isset($_GET{'maxPageLinks'})) {
    $maxPageLinks = GetParam("maxPageLinks","int","GET");
  }
  if (isset($_POST{'page'})) {
    $pageNum = GetParam("page","int","POST");
  } else if (isset($_GET{'page'})) {
    $pageNum = GetParam("page","int","GET");
  } 
  $startRow = $pageNum * $maxRows;
}
/**
function resultPagerHTML($db,$conn,$querystring,$url,$maxRows=10,$maxPageLinks=10,$pageNum=0,$urlSuffix="") {
$html = "";
  $startRow = $pageNum * $maxRows;
	$all_reg = new mysqldb;
	$all_reg->setquery($db,$conn,$querystring);
	$all_reg->disposequery();
	$totalRows = $all_reg->totalRows;
	if ($totalRows > 0 and $maxRows > 0) {
		$totalPages = ceil($totalRows/$maxRows)-1;
	} else {
		$totalPages = 0;
	}
// 	$currentPage = $MBCONFIG{'MODULE_INDEX'};
	$linkoffset = 5;
	if ($pageNum > $linkoffset) {
		$i = ($pageNum-$linkoffset);
		//also we should be showing the 'first page' link as well as the 'last page' link (see below)
	} else if ($pageNum > 0) {
		$i=$pageNum;
	}

	if ($pageNum <= $linkoffset) {
		$i=0;
	}
	
	if ($totalPages) {
		$html .= "<p>\n";
		$html .= "Go To Page : ";
		if ($pageNum > $linkoffset) {
			$html .= "<a href='{$url}&page=0{$urlSuffix}' class='pager-page-link-first'>First Page</a>";
		}
		do {
		if ($i <> $pageNum) { 
		$html .= "<a href='{$url}&page={$i}{$urlSuffix}' class='pager-page-link'>{$i}</a>";
		} else {
		$html .= "<span class='pager-page-link-current'>{$i}</span>";
		}
		$i++;
		} while (($i <= $totalPages) and ($i <= ($maxPageLinks + $pageNum)));
		if (($totalPages > $maxPageLinks) and ($pageNum < $totalPages)) {
			//we are showing the '...', last
	// 		$html .= "...";
			$html .= "<a href='{$url}&page={$totalPages}{$urlSuffix}' class='pager-page-link-last'>Last Page</a>&nbsp;<em>({$totalPages})</em>";
		}
		$html .= "</p>\n";
	} // if $totalPages
	
return $html;
}
function resultPagerHTMLmulti($db,$conn,$querystring,$url,$maxRows=10,$maxPageLinks=10,$pageNum=0,$urlSuffix="",$vars=null) {
$html = "";
if ($vars != null) {
	if (isset($vars{'pagenum'})) {
		$startRow = $pageNum * $maxRows;
		$all_reg = new mysqldb;
		$all_reg->setquery($db,$conn,$querystring);
		$all_reg->disposequery();
		$totalRows = $all_reg->totalRows;
		if ($totalRows > 0 and $maxRows > 0) {
			$totalPages = ceil($totalRows/$maxRows)-1;
		} else {
			$totalPages = 0;
		}
	// 	$currentPage = $MBCONFIG{'MODULE_INDEX'};
		$linkoffset = 5;
		if ($pageNum > $linkoffset) {
			$i = ($pageNum-$linkoffset);
			//also we should be showing the 'first page' link as well as the 'last page' link (see below)
		} else if ($pageNum > 0) {
			$i=$pageNum;
		}

		if ($pageNum <= $linkoffset) {
			$i=0;
		}
		$html .= "<p>\n";
		$html .= "Go To Page : ";
		if ($pageNum > $linkoffset) {
			$html .= "<a href='{$url}&".$vars{'pagenum'}."=0{$urlSuffix}' class='pager-page-link-first'>First Page</a>";
		}
		do {
		if ($i <> $pageNum) { 
		$html .= "<a href='{$url}&".$vars{'pagenum'}."={$i}{$urlSuffix}' class='pager-page-link'>{$i}</a>";
		} else {
		$html .= "<span class='pager-page-link-current'>{$i}</span>";
		}
		$i++;
		} while (($i <= $totalPages) and ($i <= ($maxPageLinks + $pageNum)));
		if (($totalPages > $maxPageLinks) and ($pageNum < $totalPages)) {
			//we are showing the '...', last
	// 		$html .= "...";
			$html .= "<a href='{$url}&".$vars{'pagenum'}."={$totalPages}{$urlSuffix}' class='pager-page-link-last'>Last Page</a>&nbsp;<em>({$totalPages})</em>";
		}
		$html .= "</p>\n";
	}//isset vars pagenum
} else {
	//$html .= "<p>vars is null</p>\n";
}
	
return $html;
}
function setupPagerParamsMulti(&$maxRows, &$maxPageLinks,&$pageNum,&$startRow,$vars=null) {
	if ($vars!=null) {
		if (isset($vars{'maxrows'})) {
			if (isset($_POST{$vars{'maxrows'}})) {
				$maxRows = GetParam($vars{'maxrows'},'int','POST');
			} else if (isset($_GET{$vars{'maxrows'}})) {
				$maxRows = GetParam($vars{'maxrows'},'int','GET');
			}			
		}//isset vars maxrows
		if (isset($vars{'maxpagelinks'})) {
			if (isset($_POST{$vars{'maxpagelinks'}})) {
				$maxPageLinks = GetParam($vars{'maxpagelinks'},'int','POST');
			} else if (isset($_GET{$vars{'maxpagelinks'}})) {
				$maxPageLinks = GetParam($vars{'maxpagelinks'},'int','GET');
			}	
		}// isset vars maxpagelinks
		if (isset($vars{'pagenum'})) {
			if (isset($_POST{$vars{'pagenum'}})) {
				$pageNum = GetParam($vars{'pagenum'},'int','POST');
			} else if (isset($_GET{$vars{'pagenum'}})) {
				$pageNum = GetParam($vars{'pagenum'},'int','GET');
			}
		}//isset vars pagenum
		if (isset($vars{'startrow'})) {
			if (isset($_POST{$vars{'startrow'}})) {
				$startRow = GetParam($vars{'startrow'},'int','POST');
			} else if (isset($_GET{$vars{'startrow'}})) {
				$startRow = GetParam($vars{'startrow'},'int','GET');
			}
		}//isset vars startrow
		$startRow = $pageNum * $maxRows;
	}//vars not null
}
**/
?>
